package com.itany.jdbc;

import com.itany.exception.DataAccessException;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/11/11 10:11
 * Version:1.0-SNAPSHOT
 * Description:
 */
public class JDBCUtil {

    private static Properties p;

    static {
        p = new Properties();
        try {
            p.load(JDBCUtil.class.getClassLoader().getResourceAsStream("dataSource.properties"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("JDBCUtil初始化失败");
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection(){
        try {
            String driverClassName = p.getProperty("driverClassName");
            if(driverClassName != null){
                Class.forName(p.getProperty("driverClassName"));
            }
            return DriverManager.getConnection(p.getProperty("url"),p.getProperty("username"),p.getProperty("password"));
        } catch (ClassNotFoundException e) {
            throw new DataAccessException("未找到驱动异常");
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        }
    }

    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new DataAccessException("释放连接失败");
            }
        }
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                throw new DataAccessException("释放状态集失败");
            }
        }
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new DataAccessException("释放结果集失败");
            }
        }
    }
}
